/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojos.Customers;
import pojos.Employees;
import pojos.Projects;
import pojos.SourceCode;
import java.util.ArrayList;
import java.util.Collection;
import pojos.TimeLog;
import pojos.Expenses;

/**
 *
 * @author A7med Kotb
 */
public class ProjectsJpaController implements Serializable {

    public ProjectsJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Projects projects) throws RollbackFailureException, Exception {
        if (projects.getSourceCodeCollection() == null) {
            projects.setSourceCodeCollection(new ArrayList<SourceCode>());
        }
        if (projects.getTimeLogCollection() == null) {
            projects.setTimeLogCollection(new ArrayList<TimeLog>());
        }
        if (projects.getExpensesCollection() == null) {
            projects.setExpensesCollection(new ArrayList<Expenses>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Customers customer = projects.getCustomer();
            if (customer != null) {
                customer = em.getReference(customer.getClass(), customer.getCustId());
                projects.setCustomer(customer);
            }
            Employees createdBy = projects.getCreatedBy();
            if (createdBy != null) {
                createdBy = em.getReference(createdBy.getClass(), createdBy.getEmpId());
                projects.setCreatedBy(createdBy);
            }
            Collection<SourceCode> attachedSourceCodeCollection = new ArrayList<SourceCode>();
            for (SourceCode sourceCodeCollectionSourceCodeToAttach : projects.getSourceCodeCollection()) {
                sourceCodeCollectionSourceCodeToAttach = em.getReference(sourceCodeCollectionSourceCodeToAttach.getClass(), sourceCodeCollectionSourceCodeToAttach.getScId());
                attachedSourceCodeCollection.add(sourceCodeCollectionSourceCodeToAttach);
            }
            projects.setSourceCodeCollection(attachedSourceCodeCollection);
            Collection<TimeLog> attachedTimeLogCollection = new ArrayList<TimeLog>();
            for (TimeLog timeLogCollectionTimeLogToAttach : projects.getTimeLogCollection()) {
                timeLogCollectionTimeLogToAttach = em.getReference(timeLogCollectionTimeLogToAttach.getClass(), timeLogCollectionTimeLogToAttach.getTlId());
                attachedTimeLogCollection.add(timeLogCollectionTimeLogToAttach);
            }
            projects.setTimeLogCollection(attachedTimeLogCollection);
            Collection<Expenses> attachedExpensesCollection = new ArrayList<Expenses>();
            for (Expenses expensesCollectionExpensesToAttach : projects.getExpensesCollection()) {
                expensesCollectionExpensesToAttach = em.getReference(expensesCollectionExpensesToAttach.getClass(), expensesCollectionExpensesToAttach.getExpId());
                attachedExpensesCollection.add(expensesCollectionExpensesToAttach);
            }
            projects.setExpensesCollection(attachedExpensesCollection);
            em.persist(projects);
            if (customer != null) {
                customer.getProjectsCollection().add(projects);
                customer = em.merge(customer);
            }
            if (createdBy != null) {
                createdBy.getProjectsCollection().add(projects);
                createdBy = em.merge(createdBy);
            }
            for (SourceCode sourceCodeCollectionSourceCode : projects.getSourceCodeCollection()) {
                Projects oldProjectCodeOfSourceCodeCollectionSourceCode = sourceCodeCollectionSourceCode.getProjectCode();
                sourceCodeCollectionSourceCode.setProjectCode(projects);
                sourceCodeCollectionSourceCode = em.merge(sourceCodeCollectionSourceCode);
                if (oldProjectCodeOfSourceCodeCollectionSourceCode != null) {
                    oldProjectCodeOfSourceCodeCollectionSourceCode.getSourceCodeCollection().remove(sourceCodeCollectionSourceCode);
                    oldProjectCodeOfSourceCodeCollectionSourceCode = em.merge(oldProjectCodeOfSourceCodeCollectionSourceCode);
                }
            }
            for (TimeLog timeLogCollectionTimeLog : projects.getTimeLogCollection()) {
                Projects oldProjectOfTimeLogCollectionTimeLog = timeLogCollectionTimeLog.getProject();
                timeLogCollectionTimeLog.setProject(projects);
                timeLogCollectionTimeLog = em.merge(timeLogCollectionTimeLog);
                if (oldProjectOfTimeLogCollectionTimeLog != null) {
                    oldProjectOfTimeLogCollectionTimeLog.getTimeLogCollection().remove(timeLogCollectionTimeLog);
                    oldProjectOfTimeLogCollectionTimeLog = em.merge(oldProjectOfTimeLogCollectionTimeLog);
                }
            }
            for (Expenses expensesCollectionExpenses : projects.getExpensesCollection()) {
                Projects oldProjectOfExpensesCollectionExpenses = expensesCollectionExpenses.getProject();
                expensesCollectionExpenses.setProject(projects);
                expensesCollectionExpenses = em.merge(expensesCollectionExpenses);
                if (oldProjectOfExpensesCollectionExpenses != null) {
                    oldProjectOfExpensesCollectionExpenses.getExpensesCollection().remove(expensesCollectionExpenses);
                    oldProjectOfExpensesCollectionExpenses = em.merge(oldProjectOfExpensesCollectionExpenses);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Projects projects) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Projects persistentProjects = em.find(Projects.class, projects.getProId());
            Customers customerOld = persistentProjects.getCustomer();
            Customers customerNew = projects.getCustomer();
            Employees createdByOld = persistentProjects.getCreatedBy();
            Employees createdByNew = projects.getCreatedBy();
            Collection<SourceCode> sourceCodeCollectionOld = persistentProjects.getSourceCodeCollection();
            Collection<SourceCode> sourceCodeCollectionNew = projects.getSourceCodeCollection();
            Collection<TimeLog> timeLogCollectionOld = persistentProjects.getTimeLogCollection();
            Collection<TimeLog> timeLogCollectionNew = projects.getTimeLogCollection();
            Collection<Expenses> expensesCollectionOld = persistentProjects.getExpensesCollection();
            Collection<Expenses> expensesCollectionNew = projects.getExpensesCollection();
            List<String> illegalOrphanMessages = null;
            for (SourceCode sourceCodeCollectionOldSourceCode : sourceCodeCollectionOld) {
                if (!sourceCodeCollectionNew.contains(sourceCodeCollectionOldSourceCode)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain SourceCode " + sourceCodeCollectionOldSourceCode + " since its projectCode field is not nullable.");
                }
            }
            for (TimeLog timeLogCollectionOldTimeLog : timeLogCollectionOld) {
                if (!timeLogCollectionNew.contains(timeLogCollectionOldTimeLog)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain TimeLog " + timeLogCollectionOldTimeLog + " since its project field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (customerNew != null) {
                customerNew = em.getReference(customerNew.getClass(), customerNew.getCustId());
                projects.setCustomer(customerNew);
            }
            if (createdByNew != null) {
                createdByNew = em.getReference(createdByNew.getClass(), createdByNew.getEmpId());
                projects.setCreatedBy(createdByNew);
            }
            Collection<SourceCode> attachedSourceCodeCollectionNew = new ArrayList<SourceCode>();
            for (SourceCode sourceCodeCollectionNewSourceCodeToAttach : sourceCodeCollectionNew) {
                sourceCodeCollectionNewSourceCodeToAttach = em.getReference(sourceCodeCollectionNewSourceCodeToAttach.getClass(), sourceCodeCollectionNewSourceCodeToAttach.getScId());
                attachedSourceCodeCollectionNew.add(sourceCodeCollectionNewSourceCodeToAttach);
            }
            sourceCodeCollectionNew = attachedSourceCodeCollectionNew;
            projects.setSourceCodeCollection(sourceCodeCollectionNew);
            Collection<TimeLog> attachedTimeLogCollectionNew = new ArrayList<TimeLog>();
            for (TimeLog timeLogCollectionNewTimeLogToAttach : timeLogCollectionNew) {
                timeLogCollectionNewTimeLogToAttach = em.getReference(timeLogCollectionNewTimeLogToAttach.getClass(), timeLogCollectionNewTimeLogToAttach.getTlId());
                attachedTimeLogCollectionNew.add(timeLogCollectionNewTimeLogToAttach);
            }
            timeLogCollectionNew = attachedTimeLogCollectionNew;
            projects.setTimeLogCollection(timeLogCollectionNew);
            Collection<Expenses> attachedExpensesCollectionNew = new ArrayList<Expenses>();
            for (Expenses expensesCollectionNewExpensesToAttach : expensesCollectionNew) {
                expensesCollectionNewExpensesToAttach = em.getReference(expensesCollectionNewExpensesToAttach.getClass(), expensesCollectionNewExpensesToAttach.getExpId());
                attachedExpensesCollectionNew.add(expensesCollectionNewExpensesToAttach);
            }
            expensesCollectionNew = attachedExpensesCollectionNew;
            projects.setExpensesCollection(expensesCollectionNew);
            projects = em.merge(projects);
            if (customerOld != null && !customerOld.equals(customerNew)) {
                customerOld.getProjectsCollection().remove(projects);
                customerOld = em.merge(customerOld);
            }
            if (customerNew != null && !customerNew.equals(customerOld)) {
                customerNew.getProjectsCollection().add(projects);
                customerNew = em.merge(customerNew);
            }
            if (createdByOld != null && !createdByOld.equals(createdByNew)) {
                createdByOld.getProjectsCollection().remove(projects);
                createdByOld = em.merge(createdByOld);
            }
            if (createdByNew != null && !createdByNew.equals(createdByOld)) {
                createdByNew.getProjectsCollection().add(projects);
                createdByNew = em.merge(createdByNew);
            }
            for (SourceCode sourceCodeCollectionNewSourceCode : sourceCodeCollectionNew) {
                if (!sourceCodeCollectionOld.contains(sourceCodeCollectionNewSourceCode)) {
                    Projects oldProjectCodeOfSourceCodeCollectionNewSourceCode = sourceCodeCollectionNewSourceCode.getProjectCode();
                    sourceCodeCollectionNewSourceCode.setProjectCode(projects);
                    sourceCodeCollectionNewSourceCode = em.merge(sourceCodeCollectionNewSourceCode);
                    if (oldProjectCodeOfSourceCodeCollectionNewSourceCode != null && !oldProjectCodeOfSourceCodeCollectionNewSourceCode.equals(projects)) {
                        oldProjectCodeOfSourceCodeCollectionNewSourceCode.getSourceCodeCollection().remove(sourceCodeCollectionNewSourceCode);
                        oldProjectCodeOfSourceCodeCollectionNewSourceCode = em.merge(oldProjectCodeOfSourceCodeCollectionNewSourceCode);
                    }
                }
            }
            for (TimeLog timeLogCollectionNewTimeLog : timeLogCollectionNew) {
                if (!timeLogCollectionOld.contains(timeLogCollectionNewTimeLog)) {
                    Projects oldProjectOfTimeLogCollectionNewTimeLog = timeLogCollectionNewTimeLog.getProject();
                    timeLogCollectionNewTimeLog.setProject(projects);
                    timeLogCollectionNewTimeLog = em.merge(timeLogCollectionNewTimeLog);
                    if (oldProjectOfTimeLogCollectionNewTimeLog != null && !oldProjectOfTimeLogCollectionNewTimeLog.equals(projects)) {
                        oldProjectOfTimeLogCollectionNewTimeLog.getTimeLogCollection().remove(timeLogCollectionNewTimeLog);
                        oldProjectOfTimeLogCollectionNewTimeLog = em.merge(oldProjectOfTimeLogCollectionNewTimeLog);
                    }
                }
            }
            for (Expenses expensesCollectionOldExpenses : expensesCollectionOld) {
                if (!expensesCollectionNew.contains(expensesCollectionOldExpenses)) {
                    expensesCollectionOldExpenses.setProject(null);
                    expensesCollectionOldExpenses = em.merge(expensesCollectionOldExpenses);
                }
            }
            for (Expenses expensesCollectionNewExpenses : expensesCollectionNew) {
                if (!expensesCollectionOld.contains(expensesCollectionNewExpenses)) {
                    Projects oldProjectOfExpensesCollectionNewExpenses = expensesCollectionNewExpenses.getProject();
                    expensesCollectionNewExpenses.setProject(projects);
                    expensesCollectionNewExpenses = em.merge(expensesCollectionNewExpenses);
                    if (oldProjectOfExpensesCollectionNewExpenses != null && !oldProjectOfExpensesCollectionNewExpenses.equals(projects)) {
                        oldProjectOfExpensesCollectionNewExpenses.getExpensesCollection().remove(expensesCollectionNewExpenses);
                        oldProjectOfExpensesCollectionNewExpenses = em.merge(oldProjectOfExpensesCollectionNewExpenses);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = projects.getProId();
                if (findProjects(id) == null) {
                    throw new NonexistentEntityException("The projects with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Projects projects;
            try {
                projects = em.getReference(Projects.class, id);
                projects.getProId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The projects with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<SourceCode> sourceCodeCollectionOrphanCheck = projects.getSourceCodeCollection();
            for (SourceCode sourceCodeCollectionOrphanCheckSourceCode : sourceCodeCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Projects (" + projects + ") cannot be destroyed since the SourceCode " + sourceCodeCollectionOrphanCheckSourceCode + " in its sourceCodeCollection field has a non-nullable projectCode field.");
            }
            Collection<TimeLog> timeLogCollectionOrphanCheck = projects.getTimeLogCollection();
            for (TimeLog timeLogCollectionOrphanCheckTimeLog : timeLogCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Projects (" + projects + ") cannot be destroyed since the TimeLog " + timeLogCollectionOrphanCheckTimeLog + " in its timeLogCollection field has a non-nullable project field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Customers customer = projects.getCustomer();
            if (customer != null) {
                customer.getProjectsCollection().remove(projects);
                customer = em.merge(customer);
            }
            Employees createdBy = projects.getCreatedBy();
            if (createdBy != null) {
                createdBy.getProjectsCollection().remove(projects);
                createdBy = em.merge(createdBy);
            }
            Collection<Expenses> expensesCollection = projects.getExpensesCollection();
            for (Expenses expensesCollectionExpenses : expensesCollection) {
                expensesCollectionExpenses.setProject(null);
                expensesCollectionExpenses = em.merge(expensesCollectionExpenses);
            }
            em.remove(projects);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Projects> findProjectsEntities() {
        return findProjectsEntities(true, -1, -1);
    }

    public List<Projects> findProjectsEntities(int maxResults, int firstResult) {
        return findProjectsEntities(false, maxResults, firstResult);
    }

    private List<Projects> findProjectsEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Projects.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Projects findProjects(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Projects.class, id);
        } finally {
            em.close();
        }
    }

    public int getProjectsCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Projects> rt = cq.from(Projects.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
